import socket
import threading
import os
import time


def clear_screen():
    """清屏功能"""
    os.system('cls' if os.name == 'nt' else 'clear')


def handle_client(client_socket, client_address):
    print(f"收到来自 {client_address} 的连接")

    try:
        # 创建一个线程来处理服务器输入并发送给客户端
        input_thread = threading.Thread(
            target=server_input,
            args=(client_socket,)
        )
        input_thread.daemon = True
        input_thread.start()

        while True:
            # 接收客户端消息
            data = client_socket.recv(1024).decode('utf-8')
            if not data:
                break

            print(f"\r\n客户端说: {data}")
            print("服务端说: ", end='', flush=True)  # 重新显示输入提示
    except Exception as e:
        print(f"\n发生错误: {e}")
    finally:
        client_socket.close()
        print("\n客户端连接已关闭")


def server_input(client_socket):
    """处理服务器输入并发送到客户端"""
    try:
        while True:
            message = input("服务端说: ")
            if message.lower() == 'exit':
                break
            elif message.lower() == 'clear':
                clear_screen()
                print("聊天已清屏")
                continue
            client_socket.send(message.encode('utf-8'))
    except Exception as e:
        print(f"\n发送消息时出错: {e}")


def start_server():
    # 创建服务器套接字
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 设置端口复用，这样服务器意外断开后可以立即重用端口
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # 绑定地址和端口
    host = 'localhost'
    port = 12345
    server_socket.bind((host, port))

    # 开始监听
    server_socket.listen(1)
    clear_screen()
    print(f"服务器正在监听 {host}:{port}")
    print("输入 'exit' 退出聊天")
    print("=" * 50)

    while True:
        # 接受客户端连接
        client_socket, client_address = server_socket.accept()
        # 创建一个新线程来处理客户端连接
        client_thread = threading.Thread(
            target=handle_client,
            args=(client_socket, client_address)
        )
        client_thread.daemon = True
        client_thread.start()


if __name__ == "__main__":
    start_server()